<template>
  <div>
<!--    card组件-->
    <el-card id="search">
      <el-row>
        <el-col :span="20"><div class="grid-content bg-purple">
          <el-input v-model="searchModel.username" placeholder="用户名" clearable></el-input>
          <el-input v-model="searchModel.phone" placeholder="电话" clearable></el-input>
          <el-button @click="getUserList" type="primary" round icon="el-icon-search">搜索</el-button>
        </div></el-col>
<!--        align是对齐属性-->
        <el-col :span="4" align="right"><div class="grid-content bg-purple-light">
          <el-button @click="openEditUI(null)" type="primary" icon="el-icon-plus" circle></el-button>
        </div></el-col>
      </el-row>
    </el-card>
<!--    结果列表-->
    <el-card>
      <el-table
        :data="userList"
        stripe
        style="width: 100%">
        <el-table-column label="#" width="50px" align="center">
<!--          (pageNo - 1) * pageSize + index + 1{{scope.$index+1}},正确表示序号的表达式-->
          <template slot-scope="scope">{{(searchModel.pageNo-1) * searchModel.pageSize + scope.$index + 1}}</template>
        </el-table-column>
<!--        <el-table-column-->
<!--          prop="id"-->
<!--          label="id"-->
<!--          width="50px"-->
<!--          align="center">-->
<!--        </el-table-column>-->
<!--        <el-table-column-->
<!--          prop="avater"-->
<!--          label="头像"-->
<!--          width="140"-->
<!--          align="center">-->
<!--          <img :src="avatar" style="width:50px;height:50px;">&lt;!&ndash;margin-right:15px;margin-top:15px&ndash;&gt;-->
<!--        </el-table-column>-->
        <el-table-column
          prop="username"
          label="用户名"
          width="120"
          align="center">
        </el-table-column>
        <el-table-column
          prop="realname"
          label="姓名"
          width="80"
          align="center">
        </el-table-column>
<!--        <el-table-column-->
<!--          prop="roles"-->
<!--          label="角色"-->
<!--          width="80"-->
<!--          align="center">-->
<!--        </el-table-column>-->
        <el-table-column
          prop="status"
          label="用户状态"
          width="90"
          align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status==1">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="140"
          align="center">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="电话"
          width="140"
          align="center">
        </el-table-column>
        <el-table-column
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-button @click="openEditUI(scope.row.id)" type="primary" icon="el-icon-edit" circle size="mini"></el-button>
            <el-button @click="deleteUser(scope.row)" type="danger" icon="el-icon-delete" circle size="mini"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
<!--    分页组件-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
<!--    用户信息编辑对话框-->
    <el-dialog @close="clearForm" :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="userForm" :rules="rules" ref="userFormRef">
        <el-form-item prop="username" label="用户名" :label-width="formLabelWidth">
          <el-input v-model="userForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="password" v-if="userForm.id == null || userForm.id == undefined" label="登录密码" :label-width="formLabelWidth">
          <el-input type="password" v-model="userForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="realname" label="姓名" :label-width="formLabelWidth">
          <el-input v-model="userForm.realname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item  label="角色" :label-width="formLabelWidth">
          <el-checkbox-group
            style="width: 60%;"
            v-model="userForm.roleIdList"
            :max="2">
            <el-checkbox v-for="role in roleList" :label="role.roleId" :key="role.roleId">{{role.roleDesc}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="用户状态" :label-width="formLabelWidth">
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0"
            >
          </el-switch>
        </el-form-item>
<!--        <el-upload-->
<!--          ref="upload"-->
<!--          class="avatar-uploader"-->
<!--          action="#"-->
<!--          accept="image/png,image/jpg,image/jpeg"-->
<!--          :auto-upload="true"-->
<!--          :limit="1"-->
<!--          :show-file-list="false"-->
<!--          :before-upload="beforeAvatarUpload"-->
<!--          :http-request="uploadHead"-->
<!--          :on-success="handleAvatarSuccess"-->
<!--        >-->
<!--          <img v-if="userInfo.headImage" :src="userInfo.headImage" class="avatar">-->
<!--          <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--        </el-upload>-->
<!--        <el-form-item label="头像" :label-width="formLabelWidth">-->
<!--          <el-upload-->
<!--          ref="upload"-->
<!--          class="avatar-uploader"-->
<!--          :action=avatarUrl-->
<!--          :show-file-list="false"-->
<!--          :on-success="handleAvatarSuccess"-->
<!--          :before-upload="beforeAvatarUpload">-->
<!--          <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar">-->
<!--          <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--        </el-upload>-->
<!--        </el-form-item>-->
        <el-form-item prop="phone" label="电话" :label-width="formLabelWidth">
          <el-input v-model="userForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="userForm.email" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userApi from '@/api/userManage'
import roleApi from '@/api/roleManage'
// import avatar from "element-ui/packages/avatar";

export default {

  // computed: {
  //   avatar() {
  //     return avatar
  //   }
  // },
  data() {
    var checkEmail = (rule, value, callback) => {
      var reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
      if (!reg.test(value)) {
        return callback(new Error('邮箱格式错误'))
      }
      // 一定要写callback()
      callback()
    }
    return {
      imageUrl: '',
      roleList: [],
      formLabelWidth: '100px',
      userForm: {
        roleIdList: []
      },
      dialogFormVisible: false,
      title: '',
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 10
      },
      userList: [],
      // Form 组件提供了表单验证的功能，只需要通过 rules 属性传入约定的验证规则，并将 Form-Item 的 prop 属性设置为需校验的字段名即可
      // blur是指未输入就离开输入框
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        realname: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {

    // 获取所有角色列表
    getAllRoleList() {
      roleApi.getAllRoleList().then(response => {
        this.roleList = response.data
        // 打印
        console.log(this.roleList)
      })
    },
    // 删除用户信息
    deleteUser(user) {
      this.$confirm(`您确认删除用户${user.username}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.deleteUserById(user.id).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.getUserList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 分页
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      this.getUserList()
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo
      this.getUserList()
    },
    // 获取用户列表
    getUserList() {
      userApi.getUserList(this.searchModel).then(response => {
        this.userList = response.data.rows
        this.total = response.data.total
      })
    },
    // 新增或者修改用户，这里共用一个方法，只需要做判断即可
    openEditUI(id) {
      if (id == null) {
        this.title = '新增用户'
      } else {
        this.title = '修改用户'
        // 根据id查询用户数据
        userApi.getUserById(id).then(response => {
          this.userForm = response.data
        })
      }
      this.dialogFormVisible = true
    },
    // 在关闭新增页面后清除表单
    clearForm() {
      this.userForm = {
        roleIdList: []
      }
      this.$refs.userFormRef.clearValidate()
    },
    // 新增用户保存
    saveUser() {
      // 先触发表单验证
      this.$refs.userFormRef.validate((valid) => {
        if (valid) {
          // 然后提交请求给后台
          userApi.saveUser(this.userForm).then(response => {
            // 成功提示
            this.$message({
              message: response.message,
              type: 'success'
            })
            // 关闭对话框
            this.dialogFormVisible = false
            // 刷新表格
            this.getUserList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  },

  created() {
    this.getUserList()
    this.getAllRoleList()
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
#search .el-input{
  width: 150px;
  margin-right: 10px;
}
.el-dialog .el-input{
  width: 60%;
}
</style>
